package club.zhcs.captrue.module;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.View;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Attr;
import org.nutz.mvc.annotation.Param;

import club.zhcs.capture.bean.auth.User;
import club.zhcs.capture.biz.auth.IShiroUserService;
import club.zhcs.capture.vo.Consts.InstalledRoles;
import club.zhcs.capture.vo.Consts.SessionKeys;
import club.zhcs.capture.vo.MenuNode;

import com.dgj.DefaultDESKey;
import com.dgj.nutz.module.base.AbstractBaseModule;
import com.dgj.utils.encode.DES;
import com.dgj.utils.entries.Result;

@At("/system")
public class SystemModule extends AbstractBaseModule {

	@Inject
	IShiroUserService shiroUserService;

	@Inject
	Dao dao;

	@Override
	public String _getNameSpace() {
		return "main";
	}

	/**
	 * 登出
	 * 
	 * @param session
	 * @return
	 */
	@At
	public Result logout(HttpSession session) {
		// session.invalidate();
		Subject subject = SecurityUtils.getSubject();
		subject.logout(); // session 会销毁，在SessionListener监听session销毁，清理权限缓存
		if (log.isDebugEnabled()) {
			log.debug("用户退出登录");
		}
		return Result.success();
	}

	/**
	 * 登录
	 * 
	 * @param username
	 * @param password
	 * @param remember
	 * @return
	 */
	@At
	public View login(@Param("username") String username, @Param("password") String password, @Param("remember") boolean remember) {

		Result result = shiroUserService.login(username, password);
		if (result.isSuccess()) {
			User user = (User) result.getData().get("loginUser");
			_putSession(SessionKeys.SESSION_USER_KEY, result.getData().get("loginUser"));
			List<MenuNode> menuNodes = (List<MenuNode>) Mvcs.getReq().getSession().getAttribute(SessionKeys.SESSION_MENU_KEY);// 获取菜单
			if (menuNodes == null) {
				menuNodes = shiroUserService.getMenu(user.getId());
				_putSession(SessionKeys.SESSION_MENU_KEY, menuNodes);
			}
			if (remember) {
				_addCookie("dgj_titans", DES.encrypt(username + ":" + password, DefaultDESKey.getKey()), 2 * 7 * 24 * 3600);
			}
			return _renderRedirct("/system/main");
		}
		return _renderForward("/", result.getReason());
	}

	@At
	public View main(@Attr(SessionKeys.SESSION_USER_KEY) User user) {
		if (shiroUserService.checkRole(InstalledRoles.ADMIN.toRole().getName(), user.getId())) {
			return _renderRedirct("/image/list");
		}
		return _renderRedirct("/image/list");
	}

}
